﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

namespace OpenPhotoAlbum.Controls.PhotoProcessors
{
	public abstract class Offset : IPhotoProcessor
    {
        #region IPhotoProcessor Members

        public byte[] Process(byte[] input)
        {
            MemoryStream ms = new MemoryStream(input);
            Bitmap source = new Bitmap(ms);

            int width = source.Width;
            int height = source.Height;

            OffsetMatrix = new Point[height, width];

            ConfigureOffsetMatrix(OffsetMatrix, width, height);

			DateTime t1 = DateTime.UtcNow;

            Color[,] srcMatrix = new Color[height, width];

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    srcMatrix[y, x] = source.GetPixel(x, y);
                }
            }

			DateTime t2 = DateTime.UtcNow;

            Bitmap canvas = new Bitmap(width, height);
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    Point srcPoint = OffsetMatrix[y, x];
                    canvas.SetPixel(x, y, srcMatrix[srcPoint.Y, srcPoint.X]);
                }
            }

			DateTime t3 = DateTime.UtcNow;
            System.Diagnostics.Debug.WriteLine(t2.Subtract(t1).TotalMilliseconds);
            System.Diagnostics.Debug.WriteLine(t3.Subtract(t2).TotalMilliseconds);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            //find the encoder with the image/jpeg mime-type
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                    ici = codec;
            }

            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)BusinessLogics.PhotoManager.JPEG_QUALITY);

            MemoryStream msResult = new MemoryStream();
            canvas.Save(msResult, ici, ep);

            canvas.Dispose();
            source.Dispose();
            ms.Close();

            return msResult.ToArray();
        }

        #endregion

        private Point[,] OffsetMatrix { get; set; }

        public abstract void ConfigureOffsetMatrix(Point[,] offsetMatrix, int width, int height);
    }
}
